//
//  WBOAuthController.swift
//  weibo
//
//  Created by Felix on 16/11/15.
//  Copyright © 2016年 Felix. All rights reserved.
//

import UIKit
import SVProgressHUD
class WBOAuthController: UIViewController {

    @IBOutlet var webView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()

        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APP_KEY)&response_type=code&redirect_uri=\(WB_REDIRECT_URI)"
       
        guard let url =  NSURL.init(string: urlStr) else {
            return
        }
        let request =  URLRequest.init(url: url as URL)
        webView.loadRequest(request)
        
    }

   
    @IBAction func closeButtonClick() {
        dismiss(animated: true, completion: nil)
    }

}

extension WBOAuthController:UIWebViewDelegate{
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD .show(withStatus: "正在加载...")
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        //1.判断是否授权回调页
        guard let url = request.url?.absoluteString else {
            return false
        }
        
        if !url.hasPrefix(WB_REDIRECT_URI) {
            return true
        }
        
        
        //1.判断授权回调页是否包含“code=”
        let keyStr = "code="
        guard let str = request.url?.query else {
            return false
        }
        
        if str.hasPrefix(keyStr){
            let key = str.substring(from: keyStr.endIndex)
            loadUserAccessToken(codeStr: key)
            return false
        }
        
        AdaLog(message: url)
        
        return true
    }
    
    func loadUserAccessToken(codeStr:String?) {
        guard let code = codeStr else {
            return
        }
        
        let urlStr  = "oauth2/access_token"
        let params  = ["client_id":WB_APP_KEY,"client_secret":WB_APP_SECRET,"grant_type":"authorization_code","code":code,"redirect_uri":WB_REDIRECT_URI]
        
        WBNetWorkTool.shareInstance.post(urlStr, parameters: params, progress: { (progress: Progress) in
            
            }, success: { (task:URLSessionDataTask, objc:Any?) in
                let dict = objc as? [String:Any]
                let account = WBUserAccount.init(dict: dict!)
                account.loadUserInfo(finished: { (account, error) in
                    account?.saveAccount()
                    
                    NotificationCenter.default.post(name: NSNotification.Name.init(WBSwitchRootViewController), object: false)
                   self.closeButtonClick()
                })
                AdaLog(message: WBUserAccount.loadUserAccount())
        }) { (task:URLSessionDataTask?, error:Error) in
            AdaLog(message: "出错了")
        };
//        必选	类型及范围	说明
//        client_id	true	string	申请应用时分配的AppKey。
//        client_secret	true	string	申请应用时分配的AppSecret。
//        grant_type	true	string	请求的类型，填写authorization_code
//        
//        grant_type为authorization_code时
//        必选	类型及范围	说明
//        code	true	string	调用authorize获得的code值。
//        redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
    }
}
